package com.saxon.shiro.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    /*shiro 三大对象
     * 1.Subject =============>ShiroFilterFactoryBean
     * 2.SecurityManger==============>DefaultWebSecurityManager
     * 3.realm====================>extends AuthorizingRealm
     * 获得顺序相反
     * @Qualifier指定的使方法名，可以通过@Bean(name="")来改变方法名注入
     * */

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean ();
        shiroFilterFactoryBean.setSecurityManager (defaultWebSecurityManager);
        //设置权限登录
        Map<String, String> filterMap=new IdentityHashMap<> ();
        filterMap.put ("/test/1","port[8080]");
        filterMap.put ("/test/1","perms[user:add]");

        shiroFilterFactoryBean.setFilterChainDefinitionMap (filterMap);
        shiroFilterFactoryBean.setLoginUrl ("/tologin");

        shiroFilterFactoryBean.setUnauthorizedUrl ("/404");
        return shiroFilterFactoryBean;
    }


    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager (@Qualifier ("myRealm") MyRealm myRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager ();
        defaultWebSecurityManager.setRealm (myRealm);
        return defaultWebSecurityManager;
    }

    @Bean
    public MyRealm myRealm () {
        return new MyRealm ();
    }
}
